let db = require("../db/db")
let rights_handler = require("./rights_handler")

rights_handler.set_db(db);

let handle = async function (action, data, login_info, req, res) {
	let user_id = login_info.user_id;
	switch (action) {
		case "save":
			let one_value = data.one_value;
			let tree = data.tree;
			let r = data.r;
			let tablename = r.model_table_name;
			let one_field = r.one_field;
			let multi_field = r.multi_field;
			if (!one_value) {
				throw Error('先选择主表记录');
			}
			let rights = await rights_handler.get_table_data_rights(tablename, user_id);
			if (rights instanceof Error) { return (rights); }
			if (!rights.改) {
				return (Error("没有此关系表修改权限：ID " + tablename));
			}
			let multi_values = tree.split(",").filter(n => n);
			let sql = "select * from " + db.escapeId(tablename) + " where " + db.escapeId(one_field) + "=" + db.escape(one_value);
			let recover_sql = "", del_sql = "", insert_sql = "";
			let result = await db.query(sql, []);
			for (let row of result.rows) {
				let is_deleted = row.is_deleted;
				let multi_value = row[multi_field];
				if (multi_values.includes(multi_value) && is_deleted == 1) {
					recover_sql += "update " + db.escapeId(tablename) + " set is_deleted=0, update_user=" + db.escape(user_id) + " where \
						"+ db.escapeId(one_field) + "=" + db.escape(one_value) + " and " + db.escapeId(multi_field) + "=" + db.escape(multi_value) + "; ";
				}
				if (!multi_values.includes(multi_value) && is_deleted == 0) {
					del_sql += "update " + db.escapeId(tablename) + " set is_deleted=1, update_user=" + db.escape(user_id) + " where \
						"+ db.escapeId(one_field) + "=" + db.escape(one_value) + " and " + db.escapeId(multi_field) + "=" + db.escape(multi_value) + "; ";
				}
			}
			for (let multi_value of multi_values) {
				let find = result.rows.find(r => r[multi_field] == multi_value);
				if (!find || find.length == 0) {
					insert_sql += "insert into " + db.escapeId(tablename) + " (" + db.escapeId(one_field) + "," + db.escapeId(multi_field) + ",create_user) \
						values ("+ db.escape(one_value) + "," + db.escape(multi_value) + "," + db.escape(user_id) + "); ";
				}
			}
			let sum_sql = recover_sql + del_sql + insert_sql
			if (sum_sql.length > 0) {
				result = db.multiupdate(sum_sql, []);
				return result;
			}
			else {
				return ("ok");
			}
			break;
		default:
			return (Error('未知的action:' + action));
	}
}

module.exports = { handle };